
package com.android.study;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;

public class TestProvider extends ContentProvider implements BaseColumns {
    public static final String DATABASE_NAME = "notes.db";
    public static final String TABLE_NAME = "notes";
    public static final String NOTE = "content";
    public static final String ORDER_BY_ID_ASC = _ID + " ASC";
    public static final String ORDER_BY_ID_DESC = _ID + " DESC";

    public static final String AUTHORITY = "com.android.basic.contentprovider";

    public static final int ITEMS = 1;
    public static final int ITEM_ID = 2;
    public static final int GAL_DIRECTORIES = 3;
    public static final String CONTENT_DIR_TYPE = "vnd.android.cursor.dir/vnd.basic.contentprovider";
    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.basic.contentprovider";

    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/items");

    private static final UriMatcher sUriMatcher;
    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AUTHORITY, "items", ITEMS);
        sUriMatcher.addURI(AUTHORITY, "directories", GAL_DIRECTORIES);
        sUriMatcher.addURI(AUTHORITY, "items/#", ITEM_ID);
    }

    private DatabaseHelper mSQLiteOpenHelper;

    @Override
    public boolean onCreate() {
        Logging.log(getClass(), "onCreate()");

        mSQLiteOpenHelper = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        Logging.log(getClass(), "query()");

        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        MatrixCursor mc;
        switch (sUriMatcher.match(uri)) {
            case GAL_DIRECTORIES:
                mc = new MatrixCursor(projection);
                Object[] row = new Object[projection.length];
                for (int i = 0; i < projection.length; i++) {
                    String column = projection[i];
                    if (column.equals("accountName")) {
                        row[i] = "xiaozhou@126.com";
                    } else if (column.equals("accountType")) {
                        row[i] = "com.android.test";
                    } else if (column.equals("typeResourceId")) {
                        row[i] = R.string.description;
                    } else if (column.equals("displayName")) {
                        row[i] = "displayName";
                    } else if (column.equals("exportSupport")) {
                    } else if (column.equals("shortcutSupport")) {
                    }
                }
                mc.addRow(row);
                return mc;

            case ITEMS:
                qb.setTables(TABLE_NAME);
                break;

            case ITEM_ID:
                qb.setTables(TABLE_NAME);
                qb.appendWhere(_ID + "=" + uri.getPathSegments().get(1));
                break;

            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = ORDER_BY_ID_ASC;
        } else {
            orderBy = sortOrder;
        }

        SQLiteDatabase db = mSQLiteOpenHelper.getReadableDatabase();
        Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
        return cursor;
    }

    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        Logging.log(getClass(), "delete()");

        SQLiteDatabase db = mSQLiteOpenHelper.getWritableDatabase();

        switch (sUriMatcher.match(uri)) {
            case ITEMS:
                return db.delete(TABLE_NAME, where, whereArgs);

            case ITEM_ID:
                String rowId = uri.getPathSegments().get(1);
                return db.delete(TABLE_NAME, _ID + "=" + rowId, null);

            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public String getType(Uri uri) {
        Logging.log(getClass(), "getType()");

        switch (sUriMatcher.match(uri)) {
            case ITEMS:
                return CONTENT_DIR_TYPE;

            case ITEM_ID:
                return CONTENT_ITEM_TYPE;
        }
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        Logging.log(getClass(), "insert()");

        if (sUriMatcher.match(uri) != ITEMS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        if (values.containsKey(NOTE) == false) {
            values.put(NOTE, "The Note is Null");
        }

        SQLiteDatabase db = mSQLiteOpenHelper.getWritableDatabase();
        long rowId = db.insert(TABLE_NAME, null, values);

        if (rowId > 0) {
            Uri diaryUri = ContentUris.withAppendedId(CONTENT_URI, rowId);
            return diaryUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        Logging.log(getClass(), "update()");

        SQLiteDatabase db = mSQLiteOpenHelper.getWritableDatabase();

        switch (sUriMatcher.match(uri)) {
            case ITEMS:
                return db.update(TABLE_NAME, values, where, whereArgs);
            case ITEM_ID:
                String rowId = uri.getPathSegments().get(1);
                return db.update(TABLE_NAME, values, _ID + "=" + rowId, null);
        }
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        public static final int VERSION = 3;

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, VERSION);
            Logging.log(getClass(), "DatabaseHelper()");
            getWritableDatabase();
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            String sql = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY," + NOTE
                    + " TEXT,);";
            db.execSQL(sql);
            Logging.log(getClass(), "onCreate()");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Logging.log(getClass(), "onUpgrade");
            if (oldVersion == 2) {
                Logging.log(getClass(), "oldVersion == 2");
                try {
                    db.execSQL("alter table " + TABLE_NAME + " add column " + " test1 text" + ";");
                } catch (SQLException e) {
                    Logging.log(getClass(), e.toString());
                }
                oldVersion = 3;
            }
        }
    }
}
